package com.example.a2032.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.a2032.R;
import com.example.a2032.Utils.BleSdk;
import com.example.a2032.Utils.SharedPreferenceUtils;
import com.example.a2032.Utils.Utils;
import com.example.a2032.activity.dfu.OtaActivity;
import com.example.a2032.adapter.DeviceInfoAdapter;
import com.example.a2032.db.DataDbHelper;
import com.example.a2032.entity.DeviceInfo;
import com.example.a2032.net.NetWorkUtil;
import com.example.a2032.net.FirmwareUpdateData;
import com.example.a2032.net.jstylenet.JstyleConst;
import com.example.a2032.viewmodel.DeviceInfoViewModel;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

public class DeviceInfoActivity extends BaseActivity {

    @BindView(R.id.iv_title)
    ImageView ivTitle;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.RecyclerView_DeviceInfo)
    RecyclerView RecyclerViewDeviceInfo;
    @BindArray(R.array.deviceInfoTitleArray)
    String[] deviceInfoTitles;
    @BindView(R.id.bt_firmware_update)
    Button btFirmwareUpdate;
    private DeviceInfoAdapter deviceInfoAdapter;
    private Disposable downloadDisposable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_info);
        ButterKnife.bind(this);
        init();
    }

    private static final String TAG = "DeviceInfoActivity";

    private void init() {
        subscribe(this);
        String title = getIntent().getStringExtra(SettingActivity.KEY_SettingTitle);
        tvTitle.setText(title);
        String[] contents = new String[4];
        contents[0] = getString(R.string.deviceName);
        contents[1] = "JC2032";
        contents[2] = "22:33:44:55:66:77";
        contents[3] = "V" + Utils.getAppVersion();
        deviceInfoAdapter = new DeviceInfoAdapter(deviceInfoTitles, contents);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        RecyclerViewDeviceInfo.setLayoutManager(linearLayoutManager);
        RecyclerViewDeviceInfo.setAdapter(deviceInfoAdapter);
        sendData(BleSdk.getDeviceMac());
        DeviceInfoViewModel deviceInfoViewModel = new ViewModelProvider(this).get(DeviceInfoViewModel.class);
        deviceInfoViewModel.getDeviceInfo().observe(this, new Observer<DeviceInfo>() {
            @Override
            public void onChanged(DeviceInfo deviceInfo) {
                if (deviceInfo != null) {
                    deviceInfoAdapter.updateDeviceInfo(deviceInfo);
                    queryDeviceVersion(deviceInfo.getDeviceVersion());
                }
            }
        });
    }


    String address;

    @Override
    public void DeviceAddress(String address) {
        super.DeviceAddress(address);
        // deviceInfoAdapter.updateMacAddress(address);
        DeviceInfo deviceInfo = new DeviceInfo();
        deviceInfo.setDeviceAddress(address);
        // WebSocketUtils.getInstance().sendMsg(NetSendUtils.registerDevice(Utils.getIMEI(this), address, "16675377124"));
        this.address = address;
        DataDbHelper.getInstance(this).getDeviceInfoDao().insert(deviceInfo);
        sendData(BleSdk.getDeviceVersion());
    }

    @Override
    public void DeviceVersion(String version) {
        super.DeviceVersion(version);
        DeviceInfo deviceInfo = new DeviceInfo();
        deviceInfo.setDeviceAddress(address);
        deviceInfo.setDeviceVersion(version);
        DataDbHelper.getInstance(this).getDeviceInfoDao().updateDeviceInfo(deviceInfo);
    }


    @OnClick({R.id.iv_title, R.id.bt_firmware_update})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_title:
                finish();
                break;
            case R.id.bt_firmware_update:
                toDownloadFirmware();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unSubscribe(downloadDisposable);
    }

    private void toDownloadFirmware() {
        if (TextUtils.isEmpty(downLoadUrl)) return;
        String[] filePaths = downLoadUrl.split("/");
        final String lastPath = filePaths[filePaths.length - 1];
        NetWorkUtil.getInstance().getJstyleApi().downloadPath(downLoadUrl).
                subscribeOn(Schedulers.io()).observeOn(Schedulers.io())
                .doOnNext(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(ResponseBody responseBody) throws Exception {

                        try {
                            Utils.writeToDisk(DeviceInfoActivity.this, lastPath, responseBody);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).observeOn(AndroidSchedulers.mainThread()).subscribe(new io.reactivex.Observer<ResponseBody>() {
            @Override
            public void onSubscribe(Disposable d) {
                downloadDisposable = d;
            }

            @Override
            public void onNext(ResponseBody value) {


            }

            @Override
            public void onError(Throwable e) {

                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                startActivity(WhetherUpdateActivity.class, OtaActivity.EXTRA_FILE_PATH, Utils.getFirmwarePath(DeviceInfoActivity.this) + File.separator + lastPath);
            }
        });

    }

    String downLoadUrl;
    String serviceVersion;
    long lastQueryTime = 0;

    void queryDeviceVersion(String version) {
        if (TextUtils.isEmpty(version) || System.currentTimeMillis() - lastQueryTime < 2000) return;
        String user = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.watchId);
        Log.i(TAG, "queryDeviceVersion: " + version);
        String versionCode = version.replace(".", "");
        Map<String, String> queryVersion = new HashMap<>();
        queryVersion.put(JstyleConst.KEY_DEVICE_VERSION, versionCode);
        // queryVersion.put(JstyleConst.KEY_DEVICE_VERSION, "000");
        queryVersion.put(JstyleConst.KEY_uid, TextUtils.isEmpty(user) ? "" : user);
        queryVersion.put(JstyleConst.KEY_type, "2032");
        NetWorkUtil.getInstance().getJstyleApi().queryDeviceVersion(queryVersion).
                subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new io.reactivex.Observer<FirmwareUpdateData>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(FirmwareUpdateData value) {
                int code = value.getMsgCode();

                if (code == FirmwareUpdateData.VALUE_NEED_UPDATE) {
                    initServiceVersion(value.getData().getVersion());
                    btFirmwareUpdate.setVisibility(View.VISIBLE);
                    downLoadUrl = value.getData().getUrl();
                } else {
                    btFirmwareUpdate.setVisibility(View.GONE);
                }

            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {

            }
        });
        lastQueryTime = System.currentTimeMillis();
    }

    void initServiceVersion(String version) {
        if (version.length() < 4) {
            version = "0" + version;
        }
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            stringBuffer.append(version.substring(i, i + 1)).append(i < 3 ? "." : "");
        }
        serviceVersion = stringBuffer.toString();

    }

    @Override
    protected void otaFinish() {
        super.otaFinish();
        btFirmwareUpdate.setVisibility(View.GONE);
        DeviceInfo deviceInfo = new DeviceInfo();
        deviceInfo.setDeviceAddress(address);
        deviceInfo.setDeviceVersion(serviceVersion);
        DataDbHelper.getInstance(this).getDeviceInfoDao().updateDeviceInfo(deviceInfo);
    }
}